//
//  LHPictureView.swift
//  sinaWeibo
//
//  Created by LiHong on 15/11/1.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit
import SDWebImage

//全局变量 通知
let LHPictureViewCellSelectedPictureNotification = "LHPictureViewCellSelectedPictureNotification"

let LHPictureViewCellSelectedPictureURLKey = "LHPictureViewCellSelectedPictureURLKey"

let LHPictureViewCellSelectedPictureIndexKey = "LHPictureViewCellSelectedPictureIndexKey"

class LHPictureView: UICollectionView {
    
    
    //MARK: - 属性
    var StatusPictureViewIdentifier = "StatusPictureViewIdentifier"
    var status: LHStatus? {
        didSet{
            reloadData()
        }
    }
    private var pictureLayout = UICollectionViewFlowLayout()
    //MARK: - 构造函数
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: pictureLayout)
        backgroundColor = UIColor.clearColor()
        registerClass(LHPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewIdentifier)
        dataSource = self
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 计算配图宽高
    func calcViewSize() -> CGSize {
        // 每个item的大小为90 * 90
        let itemSize = CGSize(width: 90, height: 90)
        
        pictureLayout.itemSize = itemSize
        pictureLayout.minimumLineSpacing = 0
        pictureLayout.minimumInteritemSpacing = 0
        
        // cell的间距
        let margin: CGFloat = 10
        // 列数
        let column = 3
        // 获得配图数量
        let count = status?.pictureURL?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            
            let urlString = status!.pictureURL![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
            var size = CGSize(width: 150, height: 120)
            // TODO: - 图片显示有时有误差
            
            if image != nil {
                size = image.size
          //      print("image.size = \(image.size)")
            }
            
            pictureLayout.itemSize = size
       //     print("size = \(size)")
            return size
        }
        // 图片超过一张设置间距
        pictureLayout.minimumLineSpacing = margin
        pictureLayout.minimumInteritemSpacing = margin
        
        if count == 4 {
            let width = 2 * itemSize.width + margin
            return CGSize(width: width, height: width)
        }
        
        // 其他图片数量2,3,5,6,7,8,9
        // 公式：行数 = (图片数量 + 列数 - 1) / 列数
        let row = (count + column - 1) / column
        
        let width = itemSize.width * CGFloat(column) + margin * (CGFloat(column) - 1)
        
        let height = itemSize.height * CGFloat(row) + margin * (CGFloat(row) - 1)
        
        return CGSize(width: width, height: height)
    }
}

extension LHPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURL?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewIdentifier, forIndexPath: indexPath) as! LHPictureViewCell
        
       // cell.backgroundColor = UIColor.redColor()
 //       let urlString = status?.pic_urls?[indexPath.item]["thumbnail_pic"] as! String
      //  cell.imageUrl = NSURL(string: urlString)
        let imageUrl = status?.pictureURL?[indexPath.item]
//        print("imageUrl = \(imageUrl)\ncell.imageUrl = \(cell.imageUrl)")
      //  cell.backgroundColor = UIColor.whiteColor()
        cell.imageUrl = imageUrl
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let userInfo: [String: AnyObject] = [
            LHPictureViewCellSelectedPictureURLKey: (status?.largePicURLs)!,
            LHPictureViewCellSelectedPictureIndexKey: indexPath.item
        ]
        NSNotificationCenter.defaultCenter().postNotificationName(LHPictureViewCellSelectedPictureNotification, object: self, userInfo: userInfo)
         //   NSNotificationCenter.defaultCenter().postNotificationName(LHPictureViewCellSelectedPictureNotification, object: self)
    }
    
}

class LHPictureViewCell: UICollectionViewCell {
    
    //MARK: - 属性
    var imageUrl: NSURL? {
        didSet{
            iconView.lh_setImageWithURL(imageUrl)
        //    print("imageUrl = \(imageUrl)")
        }
    }
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
       // backgroundColor = UIColor.whiteColor()
        PrepareUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 准备UI
    private func PrepareUI() {
        contentView.addSubview(iconView)
        
        iconView.ff_Fill(contentView)
    }
    
    private lazy var iconView: UIImageView = {
        let imageView = UIImageView()
        
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
    }()
}